package top.houry.netty.barrage.netty;

import cn.hutool.core.util.StrUtil;
import io.netty.handler.ipfilter.IpFilterRule;
import io.netty.handler.ipfilter.IpFilterRuleType;
import lombok.extern.slf4j.Slf4j;
import top.houry.netty.barrage.consts.BarrageRedisKeyConst;
import top.houry.netty.barrage.utils.BarrageRedisUtils;

import java.net.InetSocketAddress;

/**
 * @Desc Ip过滤器自定义设置
 * @Author houruiyang
 * @Date 2021/11/27
 **/
@Slf4j
public class WebSocketNettyServerConnectionIpFilterHandler implements IpFilterRule {

    /**
     * 定义Ip匹配规则，这里只有返回true才会执行 {@link WebSocketNettyServerConnectionIpFilterHandler#ruleType}
     *
     * @param inetSocketAddress InetSocketAddress
     * @return true-执行自定义策略 false-不执行自定义策略
     */
    @Override
    public boolean matches(InetSocketAddress inetSocketAddress) {
        String clientIp = inetSocketAddress.getAddress().getHostAddress();
        String rejectCache = BarrageRedisUtils.get(BarrageRedisKeyConst.BARRAGE_SERVER_REJECT_CONNECT_KEY + clientIp);
        if (StrUtil.isNotBlank(rejectCache)) {
            log.info("WebSocketNettyServerBaseIpFilterHandler-matches-ip:{}-黑名单-访问直接断开", clientIp);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public IpFilterRuleType ruleType() {
        return IpFilterRuleType.REJECT;
    }
}
